package com.tongcao.cn.oauth.executor;

import com.google.common.collect.Maps;
import com.tongcao.cn.oauth.handler.BaiduJumpHandler;
import com.tongcao.cn.oauth.handler.ThirdPartyHandler;
import com.tongcao.cn.oauth.request.JumpRequest;
import com.tongcao.cn.processor.BeanHelper;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author:tongcao
 * @since:2019/11/22 15:08
 * Description:
 */
public abstract class AbstractJumpExecutor<REQ extends JumpRequest, RES> implements InitializingBean, IJumpExecutor<REQ, RES> {

    @Resource
    private BeanHelper beanHelper;

    /**
     * UA检测不到时,默认的第三方处理类
     */
    protected ThirdPartyHandler defaultHandler;
    /**
     * handler容器
     */
    private Map<String, ThirdPartyHandler> handlerContainer = Maps.newConcurrentMap();

    /**
     * 重复的第三方处理类
     */
    protected Map<String, String> repeatThirdPartyAuthHandler = Maps.newHashMap();

    @Override
    public void afterPropertiesSet() throws Exception {
        final List<ThirdPartyHandler> list = beanHelper.getBeanList(ThirdPartyHandler.class);
        if (CollectionUtil.isNotEmpty(list)) {
            for (ThirdPartyHandler handler : list) {
                if (handler instanceof BaiduJumpHandler) {
                    defaultHandler = handler;
                }
                if (StringUtils.isNotBlank(handler.getCode())) {
                    if (StringUtils.isNotBlank(repeatThirdPartyAuthHandler.get(handler.getCode()))) {
                        throw new IllegalArgumentException("存在重复类型的处理器!!!!" + handler.getCode()
                                + handler.getClass().getSimpleName());
                    }
                    handlerContainer.putIfAbsent(handler.getCode(), handler);
                    repeatThirdPartyAuthHandler.putIfAbsent(handler.getCode(), handler.getClass().getSimpleName());
                }
            }
        }
        if (defaultHandler == null) {
            throw new Exception("没有默认的处理器");
        }

        if (MapUtils.isEmpty(handlerContainer)) {
            throw new Exception("初始化容器为空");
        }
    }


    public ThirdPartyHandler getHandler(String code) {
        if (StringUtils.isEmpty(code)) {
            return defaultHandler;
        }
        return handlerContainer.get(code);
    }
}